<template>
  <el-container style="height: 100vh">
    <!-- 左侧边栏 -->
    <el-aside width="300px" style="background-color: #f5f5f5; padding: 20px">
      <el-scrollbar style="height: 100%">
        <el-menu>
          <el-menu-item
            v-for="item in items"
            :key="item.id"
            @click="selectItem(item)"
            :class="{
              'is-active': selectedItem && selectedItem.id === item.id,
            }"
          >
            {{ item.title }}
          </el-menu-item>
        </el-menu>
      </el-scrollbar>
    </el-aside>

    <el-container>
      <!-- 右侧主内容区 -->
      <el-main style="padding: 20px">
        <!-- 顶部操作栏 -->
        <div
          style="
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
          "
        >
          <div>
            <el-button type="primary" @click="addItem">新增</el-button>
            <el-button :disabled="!selectedItem" @click="editItem"
              >编辑</el-button
            >
            <el-button
              type="danger"
              :disabled="!selectedItem"
              @click="deleteItem"
              >删除</el-button
            >
          </div>
          <el-input
            v-model="searchText"
            placeholder="搜索任务"
            style="width: 300px"
            clearable
          />
        </div>
        <!-- 内容展示区 -->
        <el-card v-if="selectedItem" style="min-height: 400px">
          <template #header>
            <div style="font-size: 18px; font-weight: bold">
              {{ selectedItem.title }}
            </div>
          </template>
          <div style="white-space: pre-line">
            {{ selectedItem.description }}
          </div>
        </el-card>
        <el-empty v-else description="请从左侧选择或创建任务" />
      </el-main>
    </el-container>

    <el-dialog v-model="isModalVisible" :title="modalTitle" width="50%">
      <el-form :model="modalForm" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="modalForm.title" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="modalForm.description" type="textarea" :rows="5" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup>
import { getAllTasks, createTask, updateTask, deleteTask } from "./service/api";
import { ref, computed, onMounted } from "vue";

// 数据相关
const items = ref([]);
const selectedItem = ref(null);

// 搜索关键字
const searchText = ref("");

// 模态框相关
const isModalVisible = ref(false);
const modalTitle = ref("");
const modalForm = ref({
  id: null,
  title: "",
  description: "",
});
const isEditMode = ref(false);

// 获取任务数据（分页）
const fetchTasks = async () => {
  try {
    const response = await getAllTasks();

    items.value = response.data;
  } catch (error) {
    console.error("获取任务数据失败:", error);
  }
};

// 初始加载任务数据
onMounted(async () => {
  await fetchTasks();
  // 默认选中第一个任务
  if (items.value.length > 0) {
    selectItem(items.value[0]);
  }
});

// 选中任务
const selectItem = (item) => {
  if (!item) {
    selectedItem.value = null;
    return;
  }

  if (selectedItem !== null && selectedItem.value?.id === item.id) {
    return;
  }

  console.log("当前id", selectedItem.value?.id, "点击id", item.id);

  selectedItem.value = item;
  return false;
};

// 编辑任务
const editItem = () => {
  if (selectedItem.value) {
    isEditMode.value = true;
    openModal("编辑任务", selectedItem.value);
  }
};

// 打开模态框
const openModal = (title, item = null) => {
  modalTitle.value = title;
  isModalVisible.value = true;
  modalForm.value = item
    ? { ...item }
    : { id: null, title: "", description: "" };
};

// 保存任务
const handleSave = async () => {
  try {
    if (isEditMode.value) {
      await updateTask(modalForm.value.id, modalForm.value);
    } else {
      await createTask(modalForm.value);
    }
    closeModal();
    await fetchTasks();
  } catch (error) {
    console.error("保存任务失败:", error);
  }
};

// 关闭模态框
const closeModal = () => {
  isModalVisible.value = false;
  modalForm.value = { id: null, title: "", description: "" };
  isEditMode.value = false;
};

// 新增任务
const addItem = () => {
  isEditMode.value = false;
  openModal("新增任务");
};

// 删除任务
const deleteItem = async () => {
  if (selectedItem.value && window.confirm("确定要删除该任务吗？")) {
    try {
      await deleteTask(selectedItem.value.id);
      selectedItem.value = null;
      await fetchTasks();
    } catch (error) {
      console.error("删除任务失败:", error);
    }
  }
};
</script>

<style scoped>
.el-aside {
  border-right: 1px solid #e6e6e6;
}
.is-active {
  color: #409eff;
  background-color: #ecf5ff;
}
</style>
